﻿using System;
using System.Collections.Generic;
using System.DirectoryServices;

namespace DBService
{
	internal class DomainUtils
	{
		public static List<AdModel> ReadDomain(string domainName, string userName, string userPwd)
		{
			List<AdModel> result = new List<AdModel>();
			DirectoryEntry entryOU = new DirectoryEntry();
			if (DomainUtils.IsConnected(domainName, userName, userPwd, out entryOU))
			{
				result = DomainUtils.SyncAll(entryOU);
			}
			return result;
		}

		public static bool IsConnected(string domainName, string userName, string userPwd, out DirectoryEntry domain)
		{
			domain = new DirectoryEntry();
			bool result;
			try
			{
				domain.Path = string.Format("LDAP://{0}", domainName);
				domain.Username = userName;
				domain.Password = userPwd;
				domain.AuthenticationType = AuthenticationTypes.Secure;
				domain.RefreshCache();
				result = true;
			}
			catch (Exception)
			{
				throw new Exception("连接域失败。");
			}
			return result;
		}

		public static List<AdModel> SyncAll(DirectoryEntry entryOU)
		{
			new List<AdModel>();
			return DomainUtils.SyncRootOU(new DirectorySearcher(entryOU, "(objectclass=organizationalUnit)").SearchRoot);
		}

		public static List<AdModel> SyncRootOU(DirectoryEntry entry)
		{
			List<AdModel> list = new List<AdModel>();
			if (entry.Properties.Contains("dc") && entry.Properties.Contains("objectGUID"))
			{
				string name = entry.Properties["dc"][0].ToString();
				string text = BitConverter.ToString(entry.Properties["objectGUID"][0] as byte[]);
				list.Add(new AdModel(text, name, 1, "0", ""));
				DomainUtils.SyncSubOU(entry, text, list);
			}
			return list;
		}

		public static void SyncSubOU(DirectoryEntry entry, string parentId, List<AdModel> list)
		{
			foreach (object obj in entry.Children)
			{
				DirectoryEntry directoryEntry = (DirectoryEntry)obj;
				string schemaClassName = directoryEntry.SchemaClassName;
				string[] array = directoryEntry.Name.Split(new char[]
				{
					'='
				});
				string text = array[0];
				string name = array[1];
				string id = string.Empty;
				if (directoryEntry.Properties.Contains("objectGUID"))
				{
					byte[] value = directoryEntry.Properties["objectGUID"][0] as byte[];
					id = BitConverter.ToString(value);
				}
				bool flag = list.Exists((AdModel d) => d.Id == id);
				if (!(schemaClassName == "organizationalUnit"))
				{
					if (schemaClassName == "user")
					{
						string name2 = string.Empty;
						if (directoryEntry.Properties.Contains("samaccountName"))
						{
							name2 = directoryEntry.Properties["samaccountName"][0].ToString();
						}
						if (!flag)
						{
							list.Add(new AdModel(id, name2, 2, parentId, ""));
						}
					}
				}
				else
				{
					if (!flag)
					{
						list.Add(new AdModel(id, name, 1, parentId, ""));
					}
					DomainUtils.SyncSubOU(directoryEntry, id, list);
				}
			}
		}
	}
}
